Print a Christmas tree in JavaScript


Posted by Christy on 2023-01-20

Description: Write a function named tree that accepts an number n and print a Christmas tree with the following patterns

tree(1)
*

tree(5)
    *
   ***
  *****
 *******
*********
    *
    *
    *
    *
    *
function tree(n) {
  if (n === 1) return console.log("*");
  // tree
  for (let i = 1; i <= n; i++) {
    console.log(" ".repeat(n - i) + "*".repeat(2 * i - 1));
  }

  // trunk
  for (let i = 1; i <= n; i++) {
    console.log(" ".repeat(n - 1) + "*");
  }
}

tree(5);









Related Posts

我的第一堂 - JavaScript 03 迴圈、函式

我的第一堂 - JavaScript 03 迴圈、函式

兩年過後,我能夠被稱為資深工程師了嗎?

兩年過後,我能夠被稱為資深工程師了嗎?

[閱讀組] 如何提交微開發者寫作松單篇作品?

[閱讀組] 如何提交微開發者寫作松單篇作品?


Comments